<script lang="ts" setup>
import type {
  resData,
  goodsListType,
  goodsData,
  commentDataType,
  commentListType,
  goodsFormType,
} from "../goods-manage/type";
import request from "@/utils/request";
import { ref, onMounted, reactive } from "vue";
import time from "@/utils/time";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import worksList from "@/components/worksList/worksList.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { userFormType } from "./type";
import { computed } from "vue";
import upload from "@/utils/upload";
import Upload from "@/components/upload/index.vue";
import { markRaw } from "vue";
// @ts-ignore
import empty from "@/components/empty/index.vue";
const avatarUrl = computed(() => {
  return store.state.userInfo.avatar
    ? "http://localhost:3000" + store.state.userInfo.avatar
    : "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png";
});
const router = useRouter();
const store = useStore();
const tableData = ref<goodsData[]>([]);
const goodsFrom = reactive<goodsFormType>({
  username: "",
  times: "",
  avatar: "",
  name: "",
  content: "",
  category: "",
  imageList: "",
});
const commentData = reactive<commentDataType>({
  times: new Date(),
  goodsId: "",
  username: store.state.userInfo.username,
  comment: "",
  name: store.state.userInfo.name,
  avatar: store.state.userInfo.avatar,
});
const commentValue = ref<string>("");
const commentList = ref<commentDataType[]>([]);
const dialogTableVisible = ref<boolean>(false);
// 退出登录函数
const handleLogin = () => {
  localStorage.removeItem("token");
  store.commit("clearUserInfo");
  router.push("/login");
};
// 获取个人作品函数
const getGoodsList = async () => {
  const res: goodsListType = await request.get(
    `/goods/list/${store.state.userInfo.username}`
  );
  tableData.value = res.data;
};
onMounted(() => {
  getGoodsList();
});
// 跳转作品编辑页
const handleEdit = (data: any) => {
  router.push(`/goods-manage/goodsEdit/${data.id}`);
};
// 删除作品函数
const handleDelete = async (data: any) => {
  const res = await request.delete<any, resData>(`/goods/list/${data.id}`);
  if (res.code == "200") {
    tableData.value.forEach((obj, index) => {
      if (obj.times === data.times) {
        tableData.value.splice(index, 1);
        dialogTableVisible.value = false;
      }
    });
  }
};
// 预览按钮
const handlePreview = async (data: goodsData) => {
  commentData.goodsId = data.id;
  Object.assign(goodsFrom, data);
  goodsFrom.imageList = JSON.parse(data.imageList).map(
    (url: string) => "http://localhost:3000/" + url
  );
  dialogTableVisible.value = true;
  const res = await request.get(`/goods/commentList/${commentData.goodsId}`);
  commentList.value = res.data;
};
// 发布评论按钮
const commentPost = async () => {
  commentData.comment = commentValue.value;
  const res = await request.post<any, commentListType>("/goods/comment", commentData);
  if (res.code == "200") {
    commentList.value.unshift(commentData);
    commentValue.value = "";
  }
};

const { name, username, gender, signature, avatar } = store.state.userInfo;
const userFormRef = ref();
const userForm = reactive<userFormType>({
  name,
  gender,
  signature,
  avatar,
  file: null,
  username,
});

const dialogVisible = ref(false);
const userFormRules = reactive({
  name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
  avatar: [{ required: true, message: "请选择头像", trigger: "blur" }],
  signature: [{ required: true, message: "请输入简介", trigger: "blur" }],
});

const options = [
  {
    label: "未知",
    value: "0",
  },
  {
    label: "男",
    value: "1",
  },
  {
    label: "女",
    value: "2",
  },
];
// 上传头像回调
const handleChange = (file: any) => {
  userForm.avatar = URL.createObjectURL(file);
  userForm.file = file;
};

// 更新个人信息按钮
const submitForm = () => {
  userFormRef.value.validate(async (valid: any) => {
    if (valid) {
      const res = await upload("/user/upload", userForm);
      if ((res.code = "200")) {
        store.commit("changeUserInfo", res.data);
        dialogVisible.value = false;
      }
    }
  });
};

// 退出登录按钮
const open = () => {
  ElMessageBox.confirm("你确定要退出登录吗", {
    title: "",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleLogin();
  });
};
// 删除作品按钮
const openDelete = (goodsFrom: any) => {
  ElMessageBox.confirm("你确定要删除吗？", {
    confirmButtonText: "是的",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleDelete(goodsFrom);
    ElMessage({
      type: "success",
      message: "删除成功",
    });
  });
};
// 是否发布按钮
const handleShow = async (data: any) => {
  await request.put(`/goods/isPublish`, data);
};
</script>

<template>
  <div>
    <div class="userInfoBox">
      <el-avatar :size="130" :src="avatarUrl" />
      <p>
        {{ store.state.userInfo.name ? store.state.userInfo.name : "暂未设置昵称" }}
      </p>
      <p>账号：{{ store.state.userInfo.username }}</p>

      <div>
        <el-button type="primary" round plain @click="dialogVisible = true">
          编辑资料
        </el-button>

        <el-button
          type="success"
          round
          plain
          @click="router.push('/goods-manage/goodsadd')"
          >发布作品</el-button
        >
        <el-button @click="open" type="info" round plain>退出登录</el-button>
      </div>
    </div>
    <div class="goodsBox">
      <empty v-if="tableData.length == 0"></empty>

      <div class="grid-container" v-else ref="backToTopBtn">
        <worksList v-for="item in tableData" :item="item" @click="handlePreview(item)">
          <div style="overflow: hidden">
            <el-switch
              active-value="1"
              inactive-value="0"
              v-model="item.isPublish"
              style="float: right"
              @click.stop="handleShow(item)"
              class="ml-2"
            />
          </div>
        </worksList>
      </div>
    </div>
  </div>

  <el-dialog
    class="changeUserinfoBox"
    v-model="dialogVisible"
    title=""
    width="1000"
    :show-close="false"
    style="padding-top: 60px"
  >
    <el-form
      ref="userFormRef"
      style="max-width: 600px"
      :model="userForm"
      :rules="userFormRules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="昵称" prop="name" placeholder="请输入昵称">
        <el-input v-model="userForm.name" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="userForm.gender">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="简介" prop="signature">
        <el-input v-model="userForm.signature" placeholder="请输入简介" />
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <Upload @change="handleChange" :avatar="userForm.avatar"></Upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false"> 取 消 </el-button>
        <el-button type="primary" @click="submitForm"> 确 认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    style="border-radius: 10px; padding-bottom: 16px"
    v-model="dialogTableVisible"
    :destroy-on-close="true"
    v-if="dialogTableVisible"
    :show-close="false"
    width="70vw"
    top="10vh"
  >
    <div class="left">
      <el-carousel :autoplay="false" loop height="70vh">
        <el-carousel-item
          style="height: 100%"
          v-for="item in goodsFrom.imageList"
          :key="item"
        >
          <el-image
            :src="item"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
            :preview-src-list="goodsFrom.imageList"
            :hide-on-click-modal="true"
            :preview-teleported="true"
            fit="contain"
            :initial-index="goodsFrom.imageList.indexOf(item)"
          />
        </el-carousel-item>
      </el-carousel>
    </div>
    <div class="right">
      <div class="myData">
        <el-avatar
          :src="
            goodsFrom.avatar
              ? `http://localhost:3000${goodsFrom.avatar}`
              : `http://localhost:3000${store.state.userInfo.avatar}`
          "
        />
        <span style="font-size: 15px; font-weight: 600">{{
          goodsFrom.name ? goodsFrom.name : store.state.userInfo.name
        }}</span>
      </div>
      <p class="times">{{ time(goodsFrom.times) }}</p>
      <br />
      <pre class="pre">{{ goodsFrom.content }}</pre>
      <br />
      <el-divider content-position="right">评论区</el-divider>
      <div class="commentBox">
        <div class="commentList" v-if="commentList.length != 0">
          <div class="comment" v-for="item in commentList">
            <div class="myData">
              <el-avatar :src="`http://localhost:3000${item.avatar}`" :size="28" />
              <span>{{ item.name }}</span>
            </div>
            <p style="text-align: right; color: gray; font-size: 13px">
              {{ time(item.times) }}
            </p>
            <p>{{ item.comment }}</p>
          </div>
        </div>
      </div>
      <el-input
        class="commentInput"
        v-model="commentValue"
        style="width: 100%"
        placeholder="请输入评论..."
        @keyup.enter="commentPost"
      >
      </el-input>
    </div>
    <div style="clear: both"></div>
    <template #footer>
      <el-button size="small" type="danger" @click="openDelete(goodsFrom)"
        >删除</el-button
      >
      <el-button type="primary" size="small" @click="handleEdit(goodsFrom)"
        >编辑</el-button
      >
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.myData {
  display: flex;
  align-items: center;
  padding: 5px 0 5px 5px;
  span {
    padding-left: 7px;
    font-weight: 500;
  }
}
.userInfoBox {
  padding-top: 50px;
  text-align: center;
  p {
    color: gray;
    margin: 10px 0;
    text-align: center;
  }
}
.el-form {
  margin: 0 auto;
}

:deep(.el-image) {
  width: 100%;
  height: 100%;
}
.el-carousel {
  position: relative;
}
.times {
  text-align: right;
}
.right {
  width: 40%;
  height: 70vh;
  float: right;
  display: flex;
  flex-direction: column;
  padding: 0 10px;
  position: relative;
  overflow: scroll;
  .commentBox {
    flex: 1;
    overflow: scroll;
    .comment {
      padding: 10px;
      line-height: 15px;
    }
  }
  .commentInput {
    position: sticky;
    bottom: 0;
  }
}
.left {
  width: 60%;
  height: 70vh;
  float: left;
}
:deep(.cell) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.pre {
  white-space: pre-wrap; /* 或者 pre，但 pre-wrap 会更合适 */
  word-wrap: break-word; /* 对于长单词或URL，确保它们也能换行 */
  overflow-wrap: break-word; /* 兼容性更好的替代方案 */
  font-family: "微软雅黑";
}

.grid-container {
  width: 70%;
  font-weight: 600;
  margin-top: 30px;
  column-count: 4;
  // column-width: 230px;
  column-gap: 15px;
  margin: 30px auto;
  .grid-content {
    box-sizing: border-box;
    overflow: hidden;
    margin-bottom: 10px;
    .img-box {
      border-radius: 15px;
      overflow: hidden;
    }
    .box-bottom {
      padding-left: 5px;
    }
    .box-content {
      width: 100%;
      height: 20px;
      line-height: 20px;
      white-space: normal;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 14px;
    }
  }
}
</style>
